import { getMultiData,getGoodsData } from '../../service/home.js'
// pages/home/home.js

const types = ['pop','new','sell']
const Top_DIATANCE = 1000

Page({
  
  data: {
    banners: [],
    recommends: [],
    goods:{
      'pop':{page: 0,list:[]},
      'new':{page: 0,list:[]},
      'sell':{page: 0,list:[]},
    },
    currentType: 'pop',
    titles:['流行','新款','精选'],
    show: false,
    isTabFixed: false,
    tabScrollTop: 0
  },
  onLoad: function (options) {
    this._getMultiData(),
    this._getGoodsData('pop')
    this._getGoodsData('new')
    this._getGoodsData('sell')
  },
  
  
  // ----------------------网络请求函数-----------------------
  _getMultiData(){
    getMultiData().then(res=>{
      const banners = res.data.data.banner.list;
      const recommends = res.data.data.recommend.list;
      this.setData({
        banners,
        recommends
      }) 
    })
  },
  _getGoodsData(type){
    // 获取页码
    const page = this.data.goods[type].page + 1
    //  发送网络请求
    getGoodsData(type,page).then(res=>{
      const list =  res.data.data.list
      // 将数组里的数据一个个的转入另一个数组
      const oldList = this.data.goods[type].list
      oldList.push(...list)
      const typeKey = `goods.${type}.list`
      const pageKey = `goods.${type}.page`
      this.setData({
        [typeKey]: oldList,
        [pageKey]: page
      })
    })
  },

  // -----------------------事件监听函数--------------------
  handleTabClick(event){
    const index = event.detail.index;
    console.log(index)
    this.setData({
      currentType: types[index]
    })
  },
  handImageLoad(){
      wx.createSelectorQuery().select('#tab-control').boundingClientRect(rect=>{
        this.data.tabScrollTop = rect.top
      }).exec()
    
  },
  onReachBottom(){
    this._getGoodsData(this.data.currentType)
  },
  onPageScroll(options){
    const scrollTop = options.scrollTop
    const flag = scrollTop>= Top_DIATANCE
    if(flag != this.data.show ){
      this.setData({
        show: flag
      })
    }
    const flag1 = scrollTop >= this.data.tabScrollTop 
    if(flag1 != this.data.isTabFixed){
      this.setData({
        isTabFixed: flag1
      })
    }
  }
})